<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: LeoXie <380019813@qq.com>
// +----------------------------------------------------------------------
namespace plugins\send_mobile_sms;
use cmf\lib\Plugin;
use plugins\send_mobile_sms\model\PluginMobileCodeSMSModel;
use think\Log;

/**
 * SendMobileSmsPlugin
 */
class SendMobileSmsPlugin extends Plugin
{

    public $info = [
        'name'        => 'SendMobileSms',
        'title'       => '手机服务商SMS插件',
        'description' => '手机服务商SMS插件',
        'status'      => 1,
        'author'      => 'LeoXie',
        'author_url'      => 'http://www.hctcom.com/api/SendMessage.asp',
        'version'     => '1.1.0'
    ];

    public $has_admin = 0;//插件是否有后台管理界面

    public function install() //安装方法必须实现
    {
        return true;//安装成功返回true，失败false
    }

    public function uninstall() //卸载方法必须实现
    {
        return true;//卸载成功返回true，失败false
    }

    //实现的send_mobile_verification_code钩子方法
    public function sendMobileVerificationCode($param)
    {
        $mobile        = $param['mobile'];//手机号
        $code          = $param['code'];//验证码
        $config        = $this->getConfig();
        $expire_minute = intval($config['expire_minute']);//短信保存有效期(单位：分钟)
        $expire_minute = empty($expire_minute) ? 30 : $expire_minute;//默认30分钟
        $expire_time   = time() + $expire_minute * 60;
        $result        = false;

        //Log::record($expire_time, ' [系统时间] ');
        //Log::record(time(), ' [当前时间] ');

        // $errMsg = cmf_check_verification_code($mobile, $code);
        // if (!empty($errMsg)) {
        //     $result = [
        //         'error'     => 1,
        //         'message' => $errMsg
        //     ];
        // }

        $model = new PluginMobileCodeSMSModel();
        $user_id = $config['user_id'];
        $user_name = $config['user_name'];
        $user_pwd = $config['user_pwd'];
        $smscontent = $code;
        $xml_string = $model->SendSMS($user_id, $user_name, $user_pwd, $mobile, $smscontent);

        //PHP将解析xml变为数组方法(参考：https://www.cnblogs.com/Minxiaotian/p/5131456.html)
        //$xml =simplexml_load_string($xml_string);
        //$xmljson= json_encode($xml);
        $xml=json_decode($xml_string,true);
       
        if(strtolower($xml['message'])=='ok'){
            $result = [
                'error'     => 0,
                'message' => '验证码已发送到你的手机上'
            ];
        }else{
            $result = [
                'error'     => 0,
                'message' => $xml['message']
            ];
        }

        return $result;
    }

}